package com.xjy.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class mybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static{
        InputStream inputStream = null;
        try{
            //获取sqlsession
            String resource = "mybatis-config.xml";
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (inputStream != null) {
                try{
                    inputStream.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    //sqlsession包括了所有数据库执行sql命令的方法
    public static SqlSession getSqlSession() {
        //设置自动提交
        return sqlSessionFactory.openSession(true);
    }
}

